package com.pds.web.company.controller;

import com.pds.common.annotation.Log;
import com.pds.common.constant.Constants;
import com.pds.common.core.controller.BaseController;
import com.pds.common.core.domain.R;
import com.pds.common.core.page.TableDataInfo;
import com.pds.common.enums.BusinessType;
import com.pds.common.utils.poi.ExcelUtil;
import com.pds.system.domain.FileUpload;
import com.pds.system.service.IFileUploadService;
import com.pds.utils.ExcelTemplateUtil;
import com.pds.web.company.domain.PdsCompanyDTO;
import com.pds.web.company.domain.PdsCompanyInfo;
import com.pds.web.company.service.IPdsCompanyInfoService;
import org.apache.poi.ooxml.POIXMLDocumentPart;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 企业基本信息
 */
@RestController
@RequestMapping("/companyInfo")
public class PdsCompanyInfoController extends BaseController {

    @Autowired
    private IPdsCompanyInfoService pdsCompanyInfoService;
    @Autowired
    private IFileUploadService fileUploadService;

    /**
     * 新增
     *
     * @param pdsCompanyInfo
     * @return
     */
    @Log(title = "新增企业基本信息", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('admin:company:edit')")
    @PostMapping("/add")
    public R<String> addInfo(@RequestBody PdsCompanyInfo pdsCompanyInfo) {
        Boolean result = pdsCompanyInfoService.addInfo(pdsCompanyInfo);
        if (result) {
            return R.ok("企业注册成功，账号创建成功！");
        } else {
            return R.fail("账号已存在，企业注册失败！");
        }
    }

    /**
     * 更新 -- 系统管理员
     *
     * @param pdsCompanyInfo
     * @return
     */
    @Log(title = "系统管理员更新企业基本信息", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('admin:company:edit')")
    @PostMapping("/updateByAdmin")
    public R<Boolean> updateInfoBySysAdmin(@RequestBody PdsCompanyInfo pdsCompanyInfo) {
        return R.ok(pdsCompanyInfoService.updateInfoBySysAdmin(pdsCompanyInfo));
    }

    /**
     * 禁用、启用企业
     * @param pdsCompanyInfo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('admin:company:edit')")
    @PostMapping("/updateStatus")
    public R<Boolean> updateStatus(@RequestBody PdsCompanyInfo pdsCompanyInfo) {
        pdsCompanyInfoService.updateStatus(pdsCompanyInfo.getId(), pdsCompanyInfo.getStatus());
        return R.ok();
    }

    /**
     * 更新 -- 企业管理员
     *
     * @param pdsCompanyInfo
     * @return
     */
    @Log(title = "企业管理员更新企业基本信息", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('info:edit')")
    @PostMapping("/updateByCompany")
    public R<Boolean> updateInfoByCompanyAdmin(@RequestBody PdsCompanyInfo pdsCompanyInfo) {
        return R.ok(pdsCompanyInfoService.updateInfoByCompanyAdmin(pdsCompanyInfo));
    }

    /**
     * 查询企业列表
     *
     * @param pdsCompanyInfo
     * @return
     */
    @GetMapping("/list")
    public TableDataInfo getCompanyList(PdsCompanyInfo pdsCompanyInfo) {
        startPage();
        List<PdsCompanyInfo> list = pdsCompanyInfoService.getCompanyList(pdsCompanyInfo);
        return getDataTable(list);
    }

    /**
     * 查询企业详细信息
     *
     * @param id 企业ID
     * @return
     */
    @GetMapping("/getInfoById")
    public R getInfoById(@RequestParam(name = "id", required = false) Long id) {
        PdsCompanyInfo pdsCompanyInfo = pdsCompanyInfoService.getInfoById(id);
        return R.ok(pdsCompanyInfo);
    }

    /**
     * 禁用企业
     *
     * @param pdsCompanyDTO
     * @return
     */
    @Log(title = "禁用企业", businessType = BusinessType.UPDATE)
    @PostMapping("/disableInfo")
    public R<Boolean> disableInfo(@RequestBody PdsCompanyDTO pdsCompanyDTO) {
        return R.ok(pdsCompanyInfoService.disableInfo(pdsCompanyDTO));
    }

    /**
     * 企业批量导入模板下载
     * @param response
     */
    @GetMapping("downloadTemplate")
    public void downloadTemplate(HttpServletResponse response){
        ExcelTemplateUtil.downloadTemplate(response,"companyInfoTemplate.xlsx","企业导入模板");
    }

    /**
     * 环保局批量导入运维机构
     */
    @PostMapping("batchImport")
    public R batchImport(MultipartFile file) throws Exception {
        //获取文件名+后缀
        String filename = file.getOriginalFilename();
        if (filename != null) {
            //获取其后缀
            String extension = filename.substring(filename.lastIndexOf(".") + 1);
            if (!(extension.equals("xls") || extension.equals("xlsx"))) {
                //此处为自定义异常捕获,可使用其他方式
                throw new RuntimeException("文件格式有误,请检查上传文件格式");
            }
        }
        //获取文件的输入流
        ExcelUtil excelUtil = new ExcelUtil(PdsCompanyInfo.class);
        //校验表头，防止模板被改
        String topRow = excelUtil.getTopRow(file.getInputStream());
        if(!Constants.COMPANY_INFO_HEADERS.equals(topRow)){
            throw new Exception(file.getOriginalFilename()+"文件表头被更改，请用正确的模板上传!");
        }
        //读取数据
        List<PdsCompanyInfo> list = excelUtil.importExcel(file.getInputStream());
        if(list==null && list.size()<1){
            throw new Exception(file.getOriginalFilename()+"没有读到需要导入的数据，请检查！");
        }
        Map map = saveImage(file.getInputStream());
        pdsCompanyInfoService.batchInsert(list,map);
        return R.ok();
    }

    /**
     * 企业批量导入时，保存排污许可证图片
     * @param inputStream
     * @return
     * @throws Exception
     */
    private Map saveImage(InputStream inputStream) throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Map<String, String> map = new HashMap<>();
        List<POIXMLDocumentPart> list = sheet.getRelations();
        for (POIXMLDocumentPart part : list) {
            if (part instanceof XSSFDrawing) {
                XSSFDrawing drawing = (XSSFDrawing) part;
                List<XSSFShape> shapes = drawing.getShapes();
                for (XSSFShape shape : shapes) {
                    XSSFPicture picture = (XSSFPicture) shape;
                    XSSFClientAnchor anchor = picture.getPreferredSize();
                    CTMarker marker = anchor.getFrom();
                    String key = marker.getRow() + "-" + marker.getCol();
                    byte[] data = picture.getPictureData().getData();
                    InputStream inputStream1 = new ByteArrayInputStream(data);
                    MultipartFile file1 = new MockMultipartFile( "排污许可证.png","排污许可证.png","application/octet-stream",inputStream1);
                    FileUpload fileUpload = fileUploadService.uploadAndReturnFileID(file1, "0");
                    map.put(key, fileUpload.getAttachmentId());
                }
            }
        }
        IOUtils.closeQuietly(workbook);
        IOUtils.closeQuietly(inputStream);
        return map;
    }
}
